package com.ruoyi.demo05;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Author Husp
 * @Date 2023/12/10 18:25
 */
public class Client {

    private Socket socket;

    private Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        try {
            //创建客户端对象
            Client client = new Client();
            client.start();
        } catch (IOException e) {
            throw new RuntimeException("客户端出现了异常！");
        }
    }

    private void start() throws IOException {
        socket = new Socket("127.0.0.1", 8080);
        while (true) {
            System.out.println("请选择操作选项：");
            System.out.println("1.注册");
            System.out.println("2.登录");
            System.out.println("请输入：");
            String command = scanner.next();
            switch (command) {
                case "1":
                    //注册
                    register();
                    break;
                case "2":
                    //登录
                    login();
                    break;
                case "exit":
                    System.out.println("退出成功");
                    socket.close();
                    break;
            }
        }
    }

    private void register() throws IOException {
        System.out.println("请填写注册信息~");
        //输入登录名
        System.out.println("请填写用户名：");
        String username = scanner.next();
        //输入登录密码
        System.out.println("请填写密码：");
        String password = scanner.next();
        //将登录名和密码提交给服务端
        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
        dataOutputStream.writeInt(1);
        dataOutputStream.writeUTF(username);
        dataOutputStream.writeUTF(password);
        dataOutputStream.flush();
        //接收服务端确认信号
        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
        System.out.println(dataInputStream.readUTF());
    }

    private void login() throws IOException {
        System.out.println("请填写用户名和密码~");
        //输入登录名
        System.out.println("请填写用户名：");
        String username = scanner.next();
        //输入密码
        System.out.println("请填写密码：");
        String password = scanner.next();
        //将登录名和密码提交给服务端进行判断
        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
        dataOutputStream.writeInt(2);
        dataOutputStream.writeUTF(username);
        dataOutputStream.writeUTF(password);
        dataOutputStream.flush();
        //等待服务端确认信息
        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
        System.out.println(dataInputStream.readUTF());
    }

}
